package main

import (
	"fmt"
	"net/http"
	"os"
	"path/filepath"
)

//func main() {
/*	os.Mkdir("file", 0777)
	http.Handle("/pollux/", http.StripPrefix("/pollux/", http.FileServer(http.Dir("file"))))
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
*/
/*
	// 或者使用 http.StripPrefix
	fileServer := http.StripPrefix("/pollux/", http.FileServer(http.Dir("D://LA_pro/")))
	// 设置HTTP路由
	http.Handle("/", fileServer)

	// 启动HTTP服务器
	err := http.ListenAndServe(":8180", nil)
	if err != nil {
		panic(err)
	}*/
//}

func fileHandler(w http.ResponseWriter, r *http.Request, baseDir string) {
	// 获取请求的文件路径
	requestedFile := filepath.Join(baseDir, r.URL.Path[len("/pollux/"):])

	// 处理文件请求
	http.ServeFile(w, r, requestedFile)
}

func fileListHandler(w http.ResponseWriter, r *http.Request, baseDir string) {
	// 获取当前路径
	currentPath := r.URL.Path[len("/pollux/"):]
	fullPath := filepath.Join(baseDir, currentPath)

	// 列出目录中的文件
	files, err := os.ReadDir(fullPath)
	if err != nil {
		http.Error(w, "Unable to read directory", http.StatusInternalServerError)
		return
	}

	fmt.Fprintf(w, "<h1>Files in %s</h1>", fullPath)

	// 添加返回上层目录的链接，仅在子目录中显示
	if currentPath != "" {
		parentPath := filepath.Dir(currentPath)
		fmt.Fprintf(w, "<p><a href=\"/pollux/%s\">...</a></p>", parentPath)
	}

	fmt.Fprint(w, "<ul>")
	for _, file := range files {
		if file.IsDir() {
			fmt.Fprintf(w, "<li><a href=\"/pollux/%s/\">%s/</a></li>", filepath.Join(currentPath, file.Name()), file.Name())
		} else {
			fmt.Fprintf(w, "<li><a href=\"/pollux/%s\">%s</a></li>", filepath.Join(currentPath, file.Name()), file.Name())
		}
	}
	fmt.Fprint(w, "</ul>")
}

func main() {
	// 获取当前工作目录
	baseDir, err := os.Getwd()
	if err != nil {
		panic(err)
	}

	// 文件列表处理
	http.HandleFunc("/pollux/", func(w http.ResponseWriter, r *http.Request) {
		// 检查是否是根目录请求
		if r.URL.Path == "/pollux/" {
			fileListHandler(w, r, baseDir) // 处理根目录请求
		} else {
			fileHandler(w, r, baseDir) // 处理文件请求
		}
	})

	// 启动HTTP服务器
	err = http.ListenAndServe(":8180", nil)
	if err != nil {
		panic(err)
	}
}
